<template>
  <li
    @mouseenter="mouseItem(true)"
    @mouseleave="mouseItem(false)"
    :style="{ backgroundColor: bgColor, color: myColor }"
  >
    <label>
      <input type="checkbox" v-model="isCheck"  />
      <span>{{ todo.title }}</span>
    </label>
    <button class="btn btn-danger" v-show="isShow" @click="del(todo.id)">
      删除
    </button>
  </li>
</template>

<script lang="ts">
import { computed, defineComponent, ref, toRaw } from "vue";
import { Todo } from "../types/Todo";

export default defineComponent({
  name: "Item",
  props: {
    todo: {
      type: Object as () => Todo,
      requried: true,
    },
    deleteTodo: {
      type: Function,
      required: true,
    },
    updateTodo: {
      type: Function,
      required: true,
    },
  },
  setup(props) {
    const bgColor = ref("white");
    const myColor = ref("black");
    // 删除按钮的显示 or 隐藏
    const isShow = ref(false);
    // console.log(props.todo);
    const mouseItem = (flag: boolean) => {
      if (flag) {
        // 鼠标移动到待办事项上
        // console.log("鼠标移动到待办事项上");
        bgColor.value = "pink";
        myColor.value = "white";
        isShow.value = true;
      } else {
        // 鼠标移出待办事项上
        // console.log("鼠标移出待办事项上");
        bgColor.value = "white";
        myColor.value = "black";
        isShow.value = false;
      }
    };
    // 删除待办
    const del = (id: number) => {
      // console.log('id = ', id);
      if (window.confirm("您确定要删除吗？")) {
        // 调用 todo 删除方法
        props.deleteTodo(id);
      }
    };

    // 是否选中
    const isCheck = computed({
      get() {
        return props.todo && props.todo.isCompleted;
      },
      set(val) {
        if (props.todo) {
          return props.updateTodo(props.todo.id, val);
        }
      },
    });

    return {
      bgColor,
      myColor,
      mouseItem,
      isShow,
      del,
      isCheck
    };
  },
});
</script>

<style scoped>
/*item*/
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  /* display: none; */
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}
</style>
